package com.wuwei.elearning.question.vo;

import com.wuwei.elearning.question.domain.Subject;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用于给elementUI的tree显示的vo
 */
@Data
public class SubjectVoForElementUi extends Subject {

    private String label;
    private Long value;
    private boolean canService;
    private boolean needTest;
    private List<SubjectVoForElementUi> children;


    public static List<SubjectVoForElementUi> convertToTreeElementUI(List<Subject> subjects) {
        // 创建一个Map来存储所有节点，key为id
        Map<Long, SubjectVoForElementUi> nodeMap = new HashMap<>();
        List<SubjectVoForElementUi> rootNodes = new ArrayList<>();

        // 第一步：创建所有节点
        for (Subject subject : subjects) {
            SubjectVoForElementUi node = new SubjectVoForElementUi();
            node.setLabel(subject.getName());
            node.setValue(subject.getId());
            node.setChildren(new ArrayList<>());
            node.setEndTime(subject.getEndTime());
            if (subject.getOnService()==null) {
                node.setCanService(false);
            } else {
                node.setCanService(subject.getOnService() == 1);
            }

            if (subject.getNeedTest()==null) {
                node.setNeedTest(false);
            }else {
                node.setNeedTest(subject.getNeedTest()==1);
            }

            nodeMap.put(subject.getId(), node);
        }

        // 第二步：构建树形结构
        for (Subject subject : subjects) {
            SubjectVoForElementUi currentNode = nodeMap.get(subject.getId());

            if (subject.getParentId() == null) {
                // 如果是根节点，加入根节点列表
                rootNodes.add(currentNode);
            } else {
                // 如果有父节点，将当前节点加入到父节点的children中
                SubjectVoForElementUi parentNode = nodeMap.get(subject.getParentId());
                if (parentNode != null) {
                    parentNode.getChildren().add(currentNode);
                }
            }
        }
        return rootNodes;
    }

    /**
     * 将树形结构转换为扁平化列表
     * @param root 根节点
     * @return 包含parentId的扁平化列表
     */
    public static List<SubjectVoForElementUi> flattenTree(SubjectVoForElementUi root) {
        List<SubjectVoForElementUi> result = new ArrayList<>();
        flatten(root, result, null); // 根节点的parentId为null
        return result;
    }

    private static void flatten(SubjectVoForElementUi node, List<SubjectVoForElementUi> result, Long parentId) {
        if (node == null) return;

        // 设置当前节点的parentId并加入结果集
        node.setParentId(parentId);
        result.add(node);

        // 递归处理子节点，传递当前节点ID作为子节点的parentId
        if (node.getChildren() != null) {
            for (SubjectVoForElementUi child : node.getChildren()) {
                // 将字符串类型的value转换为Long类型作为parentId
                flatten(child, result, node.getValue());
            }
        }
    }

}
